package com.etongwl.commonutils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

/**
 * SD开工具类
 */
public class SDcardUtils {
    /**
     * @return true 存在、false 不存在
     * @throws
     * @Methods: isSdCardExist
     * @Description: 检测SD卡是否存在
     */
    public static boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * sd卡可用空间
     *
     * @return sd卡总空间
     */
    public static long getAvailaleSize() {
        File path = Environment.getExternalStorageDirectory(); // 取得sdcard文件路径
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * sd卡总空间
     *
     * @return sd卡总空间
     */
    public static long getAllSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getBlockCount();
        return availableBlocks * blockSize;
    }

    /**
     * 获取应用根目录
     *
     * @param con 上下文
     * @return /data/data/xxxxxxxxxx/
     */
    public static String getPath(Context con) {
        String path = con.getFilesDir().getParent();
        return path + "/";
    }

    /**
     * 获取应用缓存目录
     *
     * @param con 上下文
     * @return /data/data/XXXXXX/Cache
     */
    public static String getCachePath(Context con) {
        String path = con.getFilesDir().getParent();
        return path+"/Cache/";
    }

    /**
     * 得到SD卡的目录
     *
     * @return /mnt/sdcard/
     */
    public static String getSDCardPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    /**
     * 保存内容到文件
     * @param filePath 文件全部路径
     * @param mContent 保存的内容
     */
    public static void saveFile(String filePath,String mContent){
        try {
            File parentDir = new File(filePath).getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            File file = new File(filePath);
            // 文件不存在时创建，存在时清空内容
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            out.write(mContent);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
